package com.ljs.module.util;

import com.ljs.module.common.PathEnum;
import com.ljs.module.entity.smartbi.ExtensionsList;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 扩展包列表工具类
 * Created by lijunsai on 2021/07/19
 */
public class ExtensionListUtil {
    // 每个标签对应的当前扩展包列表
//    public static List<ExtensionsList> extensionsLists = new ArrayList<>();
    // 每个标签对应的扩展包列表的历史记录
//    public static List<ExtensionsList> historyExtensionsLists = new ArrayList<>();
    // 全局扩展包列表历史记录
    public static List<ExtensionsList> globalHistoryExtensionsLists = new ArrayList<>();
    // extension下ext后缀文件列表(用于直接操作ext文件)
//    public static List<ExtensionsList> extFileList = new ArrayList<>();
    public static Map<String, String> listPath = new HashMap<>();
    public static String title = "";

    static {
        // 初始化 读取configListPath.txt 中的标签 读取global_history.txt 中的扩展包历史记录
        listPath.clear();
        globalHistoryExtensionsLists.clear();
        initListPathConfig();
        initGlobalHistory();
    }

    /**
     * 删除标签
     * @param title 标签
     */
    public static void deleteListPath(String title){
        ExtensionListUtil.listPath.remove(title);
        String path = PathEnum.CONFIG.getPath() + File.separator + title + "_history.txt";
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 新增标签
     * @param title 标签
     * @param path extension地址
     * @return 是否添加成功
     */
    public static boolean addListPath(String title, String path) {
        if (listPath.containsKey(title)) {
            return false;
        }
        listPath.put(title, path);
        changeListPathConfig();
        return true;
    }

//    /**
//     * 切换标签时，进行一个初始化  读取当前标签对应的扩展包列表、以及历史操作记录列表
//     * @param titleP 标签
//     */
//    public static void init(String titleP) {
//        title = titleP;
//        extensionsLists = FileUtil.loadExtList(listPath.get(titleP) + Util.replaceFileSeparor("/WEB-INF/extensions/extensions.list")
//                , Collectors.toList(), ExtensionsList::new);
//        String path = FileUtil.path + File.separator + title + "_history.txt";
//        FileUtil.fileNotExistThenMake(path);
//        historyExtensionsLists = FileUtil.loadExtList(path, Collectors.toList(), ExtensionsList::new);
//        loadExtFileList(listPath.get(titleP) + Util.replaceFileSeparor("/WEB-INF/extensions/"));
//    }

    public static List<ExtensionsList> loadExtFileList(String path, List<ExtensionsList> extensionsLists) {
        File file = new File(path);
        File[] files = file.listFiles(x -> x.getName().contains(".ext"));
        List<ExtensionsList> ext = getExt(extensionsLists);
        List<ExtensionsList> extFileList = new ArrayList<>();
        for (File file1 : files) {
            String name = file1.getName();
            ExtensionsList extensionsList1 = new ExtensionsList();
            for (ExtensionsList extensionsList : ext) {
                if (name.equals(extensionsList.getPath())) {
                    extensionsList1.setInFile(true);
                }
            }
            if (!extensionsList1.isInFile()) {
                extensionsList1.setExt(true).setShortName(name).setInFile(false).initPath(file1.getAbsolutePath());
                extFileList.add(extensionsList1);
            }
        }
        return extFileList;
    }

    /**
     * 将修改后的扩展包列表刷新到文件中
     */
    public static void change(List<ExtensionsList> extensionsLists, List<ExtensionsList> historyExtensionsLists, String title) {
        FileUtil.changeExtList(listPath.get(title) + Util.replaceFileSeparor("/WEB-INF/extensions/extensions.list")
                , extensionsLists, ExtensionsList::getPath);
        FileUtil.changeExtList(PathEnum.CONFIG.getPath() + File.separator + title + "_history.txt"
                , historyExtensionsLists, ExtensionsList::getPath);
    }

    public static void initGlobalHistory() {
        String globalHistorytPath = PathEnum.CONFIG.getPath() + File.separator + "global_history.txt";
        FileUtil.fileNotExistThenMake(globalHistorytPath);
        globalHistoryExtensionsLists = FileUtil.loadExtList(globalHistorytPath, Collectors.toList(), ExtensionsList::new);
    }

    public static void changeGlobalHistory() {
        String globalHistorytPath = PathEnum.CONFIG.getPath() + File.separator + "global_history.txt";
        FileUtil.changeExtList(globalHistorytPath, globalHistoryExtensionsLists, ExtensionsList::getPath);
    }

    /**
     * 从configListPath.txt中初始化标签集合
     */
    public static void initListPathConfig() {
        String configListPath = PathEnum.CONFIG.getPath() + File.separator + "configListPath.txt";
        File file = new File(configListPath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
            }
        } else {
            listPath = FileUtil.loadExtList(configListPath, Collectors.toMap(x -> x.split("<-#->")[0], y -> y.split("<-#->")[1],(v1,v2)->v1), x -> x);
        }
    }

    /**
     * 刷新内容到configListPath.txt文件中
     */
    public static void changeListPathConfig() {
        String configListPath = PathEnum.CONFIG.getPath() + File.separator + "configListPath.txt";
        File file = new File(configListPath);
        List<String> list = new ArrayList<>();
        Set<String> keys = listPath.keySet();
        for (String key : keys) {
            list.add(key + "<-#->" + listPath.get(key));
        }
        FileUtil.changeExtList(configListPath, list, x -> x);
    }

    public static int searchExensions(String path, boolean append){
        File file = new File(path);
        if (!file.exists()) {
            return 0;
        }
        File[] fileChildren = file.listFiles(x -> x.isDirectory());
        List<File> list = new ArrayList<>();
        for (File fileChild : fileChildren) {
            searchExensions(list, fileChild, false);
        }
        int searchCount = list.size();
        if (append) {
            Set<ExtensionsList> collect = list.stream().map(x -> new ExtensionsList(x.getAbsolutePath())).collect(Collectors.toSet());
            collect.addAll(globalHistoryExtensionsLists);
            globalHistoryExtensionsLists = collect.stream().collect(Collectors.toList());
        } else {
            globalHistoryExtensionsLists = list.stream().map(x -> new ExtensionsList(x.getAbsolutePath())).collect(Collectors.toList());
        }
        // 存入文件中
        changeGlobalHistory();
        return searchCount;
    }

    public static void searchExensions(List<File> files, File file, boolean next) {
        try {
            if (file.getName().equals("web") && next) {
                File extXmlFile = new File(file.getAbsolutePath(), File.separator + "META-INF" + File.separator + "applicationContext.xml");
                if (extXmlFile.exists()) {
                    List<String> modulePath = FileUtil.findModulePath(extXmlFile.getAbsolutePath());
                    if (modulePath != null && modulePath.size() > 0) {
                        files.add(file);
                    }
                }
                return;
            }

            if (file.getName().equals("src")) {
                File[] fileChildren = file.listFiles(x -> x.isDirectory());
                Optional<File> src = Arrays.stream(fileChildren).filter(x -> x.getName().equals("web")).findFirst();
                if (src.isPresent()) {
                    searchExensions(files, src.get(), true);
                    return;
                }
            }
            File[] fileChildren = file.listFiles(x -> x.isDirectory());
            Optional<File> src = Arrays.stream(fileChildren).filter(x -> x.getName().equals("src")).findFirst();
            if (src.isPresent()) {
                searchExensions(files, src.get(), true);
                return;
            }
            for (File fileChild : fileChildren) {
                searchExensions(files, fileChild, false);
            }
        } catch (Exception e) {
            // 搜索扩展包出现错误 直接跳过
        }

    }

    public static List<ExtensionsList> getExtensionsList(String title) {
        return FileUtil.loadExtList(listPath.get(title) + Util.replaceFileSeparor("/WEB-INF/extensions/extensions.list")
                , Collectors.toList(), ExtensionsList::new);
    }

    public static List<ExtensionsList> getHistoryExtensionsList(String title) {
        String path = PathEnum.CONFIG.getPath() + File.separator + title + "_history.txt";
        FileUtil.fileNotExistThenMake(path);
        return FileUtil.loadExtList(path, Collectors.toList(), ExtensionsList::new);
    }

    /**
     * 获取列表中不是.ext的扩展包
     * @return
     */
    public static List<ExtensionsList> getNoExt(List<ExtensionsList> extensionsLists) {
        return extensionsLists.stream().filter(x -> !x.isExt()).collect(Collectors.toList());
    }

    /**
     * 获取列表中是.ext的扩展包
     * @return
     */
    public static List<ExtensionsList> getExt(List<ExtensionsList> extensionsLists) {
        return extensionsLists.stream().filter(ExtensionsList::isExt).collect(Collectors.toList());
    }

    /**
     * 将扩展包路径转换成扩展包实体
     * @param str 扩展包数组
     * @return
     */
    public static List<ExtensionsList> splitToExtensionList(String[] str){
        return Stream.of(str).map(x -> new ExtensionsList().setPath(x)).collect(Collectors.toList());
    }

    /**
     * 重置集合
     */
    public static void reset() {
//        extensionsLists.clear();
        title = null;
    }

}
